package br.ufpe.cin.plebeia.webapp.infra;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class PathDispatchAction extends Action {

	public static final String ERRO_NAO_IDENTIFICADO = "erroNaoIdentificado";
	
	protected final Log log = LogFactory.getLog(getClass());
	
	@Override
	public ActionForward execute(ActionMapping actionMapping,
			ActionForm actionForm, HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse) throws Exception {
		ActionMessages messages = new ActionMessages();
		ActionMessages errorMessages = new ActionMessages();
		ActionErrors errors = new ActionErrors();
		ActionForward forward = actionMapping.getInputForward();
		
		Object[] objects = new Object[]{actionMapping, actionForm, httpServletRequest, httpServletResponse};
		
		try {
			String path = actionMapping.getPath().substring(1);
			ActionForward newForward = (ActionForward) MethodUtils.invokeMethod(this, path, objects);
			forward = newForward;
		} catch (Exception e) {
			Object[]parametro = {e.getMessage()};
			errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage(ERRO_NAO_IDENTIFICADO,parametro));
			errorMessages.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage(ERRO_NAO_IDENTIFICADO,parametro));
			e.printStackTrace();
		}
		this.saveMessages(httpServletRequest, messages);
		this.saveErrors(httpServletRequest, errorMessages);
		return forward;
	}

}
